<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>this</title>
  </head>
  <body>
    <script>
      //T1. 

      function fun() {
        console.log(this.s);//1
        //this指向obj
      }
      var obj = {
        s: 1,
        f: fun,
      };
      var s = 2;
      obj.f();

      //T2.
      function fun() {
        console.log(this.s);//2
        //window调用fun() this指向window
        var obj = {
          s: 1,
          f: fun,
        };
      }
      var s = 2;
      fun();

       //T3.
      var A = {
        name: "jmq",
        f: function () {
          console.log(this.name);
        },
      };
      var B = {
        name: "syc",
      };
      B.f = A.f;
      //this指向对象A
      A.f();//"jmq"
      //对象A的函数赋给了对象B this指向B
      B.f();//syc

       //T4.
      function fo() {
        console.log(this.a);
      }
      var o1 = {
        a: 3,
      };
      /**o1{
        a:3
        fo:function{
          console.log(this.a);
        }
      }
      **/
      var o2 = {
        a: 6,
      };
       /**o2{
        a:6
        fo:function{
          console.log(this.a);
        }
      }
      **/
      var a = 9;
      o1.f = fo;
      console.log(o1);
      o2.f = o1.f;
      o1.f(); // 3 
      o2.f(); // 6

      //T5.
      function foo() {
        console.log(this.a);//2
        //this指向obj2
      }
      var obj2 = {
        a: 2,
        fn: foo,
      };
      var obj1 = {
        a: 1,
        o1: obj2,
      };
      //o1指向obj2，obj2下的fn指向函数foo()
      obj1.o1.fn(); // 2
      //T6.
      var a = 10;
      var obj = {
        a: 120,
        method: function () {
          var bar = function () {
            console.log(this.a); //10
            
          };
          bar();
          //this指向obj，this.a输出120
          return this.a; // 120
        },
      };
      console.log(obj.method());//120

      //T7.
      var fullName = "language";
      var obj = {
        fullName: "javascript",
        prop: {
          getFullName: function () {
            return this.fullName;
          },
        },
      };
      //this指向prop
      console.log(obj.prop.getFullName()); // undefined

      var test = obj.prop.getFullName;
      //test()等于whindow.test();
      console.log(test()); //language

      //T8.
      function fn() {
        console.log(this);
      }
      setInterval(fn, 1000); //window
      // T9.
      var k = {
        a: 1,
        sing: function () {
          console.log(this);//this指向对象k
        },
      };
      setTimeout("k.sing()", 1000) // 一秒钟后打印对象{a:1 f}

      //T10.
      var value = 8;
      var obj = {
        value: 10,
        fn: () => {
          console.log(this.value); //8
          //箭头函数指向windo
          //函数被调用了，obj.fn()等于whindow.obj.fn()
        },
      };
      obj.fn();
    </script>
  </body>
</html>
